//-----------------------------------------------------------------------
// <copyright file="UserInterfaceHandler.cs" company="iron9light">
//      Copyright (c) iron9light. All rights reserved.
// </copyright>
// <author>iron9light</author>
//-----------------------------------------------------------------------

namespace EventBroker.Handlers
{
    using System;
    using System.Reflection;
    using System.Threading;

    /// <summary>
    /// Handler that executes the subscription synchronously on the user interface thread (Send semanthics).
    /// </summary>
    public class UserInterfaceHandler : DefaultHandler
    {
        private SynchronizationContext syncContext;

        public override Delegate SubscriptionHandler
        {
            get
            {
                return base.SubscriptionHandler;
            }

            set
            {
                base.SubscriptionHandler = value;

                // If there's a syncronization context (i.e. the WindowsFormsSynchronizationContext 
                // created to marshal back to the thread where a control was initially created 
                // in a particular thread), capture it to marshal back to it through the 
                // context, that basically goes through a Post/Send.
                if (SynchronizationContext.Current != null)
                {
                    this.syncContext = SynchronizationContext.Current;
                }
            }
        }

        public override void Handle(object sender, EventArgs e, System.Collections.Generic.ICollection<Exception> exceptions)
        {
            if (this.syncContext != null)
            {
                if (this.SubscriptionHandler != null)
                {
                    this.syncContext.Send(
                            delegate(object data)
                            {
                                try
                                {
                                    ((Delegate)data).DynamicInvoke(sender, e);
                                }
                                catch (TargetInvocationException ex)
                                {
                                    exceptions.Add(ex.InnerException);
                                }
                            },
                            this.SubscriptionHandler);
                }
                else
                {
                    base.Handle(sender, e, exceptions);
                }
            }
        }
    }
}